/*
   Copyright 2022 cmanlh

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
/**
 * message broker
 */
export default class JscMQ {
    static #register = new Map();

    /**
     * register a listener on topic
     * 
     * @param {String} topic 
     * @param {String} listenerId 
     * @param {Function} listener 
     */
    static register(topic, listenerId, listener) {
        let listenerMap = this.#register.get(topic);
        if (null == listenerMap) {
            listenerMap = new Map();
            this.#register.set(topic, listenerMap);
        }

        listenerMap.set(listenerId, listener);
    }

    /**
     * unregister from a topic
     * 
     * @param {String} topic 
     * @param {String} listenerId  
     */
    static unregister(topic, listenerId) {
        let listenerMap = this.#register.get(topic);
        if (null != listenerMap) {
            listenerMap.delete(listenerId);
            if (listenerMap.size <= 0) {
                this.#register.delete(topic);
            }
        } else {
            console.error("No listener exists for %s", topic);
        }
    }

    /**
     * post a msg to topic
     * 
     * @param {String} topic 
     * @param {Object} msg {'sender':$*, 'data':$Object}
     */
    static postMsg(topic, msg) {
        let listenerMap = this.#register.get(topic);
        if (null != listenerMap) {
            let contextMsg = { 'msg': msg, 'listenerResult': [] };
            listenerMap.forEach((listener) => {
                let result = listener.call(null, contextMsg);
                if (null != result) {
                    contextMsg.listenerResult.push(result);
                }
            });
        } else {
            console.error("No listener exists for %s", topic);
        }
    }
}